package com.anli1.timedTask;

import com.anli1.entity.pojo.Coupon;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Configuration
public class kcyure {
    @Autowired
    RedisTemplate redisTemplate;
    @XxlJob(value = "kcyure")
    public void kcyure() {
        try {
            //Set<String> couponKeys  = redisTemplate.keys("*"); // 假设你的优惠券键以 "coupon:" 开头
            //拿出同步库存表的-进行id过滤掉已经同步过的库存
            //拿去同步表ids
            Cursor<byte[]> couponKeys = redisTemplate.getConnectionFactory().getConnection().scan(ScanOptions.scanOptions().match("*coupon*").count(100).build());
            Set<String> couponKeyss = new HashSet<>();
            while (couponKeys.hasNext()) {
                byte[] key = couponKeys.next();
                String keyStr = new String(key, StandardCharsets.UTF_8); // 转换为字符串

                // 提取 coupon 后面的部分
                if (keyStr.contains("coupon")) {
                    String suffix = keyStr.substring(keyStr.indexOf("coupon") + "coupon".length());
                    couponKeyss.add(suffix);

                }
            }
            //拿去库存表
            Set<String> stocks = new HashSet<>();
            Cursor<byte[]> stocksi = redisTemplate.getConnectionFactory().getConnection()
                    .scan(ScanOptions.scanOptions().match("stock*").count(100).build());
            while (stocksi.hasNext()) {
                byte[] key = stocksi.next();
                String keyStr = new String(key, StandardCharsets.UTF_8); // 转换为字符串
                Map<Object, Object> hashEntries = redisTemplate.opsForHash().entries(keyStr);
                for(Object key1 : hashEntries.keySet())
                {
                        stocks.add(keyStr);
                }

            }
            if (couponKeyss != null) {
                for (String key : couponKeyss) {
                    if(stocks.contains(key))
                    {
                        continue;
                    }
                    Coupon coupon= (Coupon) redisTemplate.opsForValue().get("coupon"+key.toString());
                    int index = (int) (coupon.getId() % 10);
                    String resourceStockRedisKey = String.format("Stock:%s", index);
                    redisTemplate.opsForHash().put(resourceStockRedisKey, key, coupon.getAvailableStock());



                }

            }



        }catch (Exception e)
    {
        e.printStackTrace();
        System.out.println("库存同步失败");
        //异常处理
    }}}












